﻿using System.Collections.Generic;
using System.Linq;
using Myotragus.Data;
using Myotragus.Data.Containers;
using Myotragus.Data.RepositoryExtensions;
using Myotragus.Data.Util;
using Myotragus.Store.Model.Domain;
using NHibernate.Criterion;

namespace Myotragus.Store.Model.Repositories
{
  public class CategoryRepository : Repository<ICategory>, ICategoryRepository
  {
    public CategoryRepository(IEntitiesContainer entities) : base(entities)
    {
    }

    public IEnumerable<IProduct> GetProductsIn(int categoryId, int lcId, params Order[] orderBy)
    {
      return GetProductsIn(categoryId, lcId, 0, -1, orderBy);
    }

    public IEnumerable<IProduct> GetProductsIn(int categoryId, int lcId, int firstResult, int maxResults, 
      params Order[] orderBy)
    {
      var products = Services.Resolve<IProductRepository>();
      using (var session = this.OpenSession())
      {
        var criteria = CriteriaHelper.CreateCriteria(session, typeof(CategoryProducts), 
          firstResult, maxResults, orderBy);
        
        criteria.CreateAlias("Products", "Product");

        LocalizableCriteriaHelper.AddAliases(products, criteria, "Product", lcId);
        LocalizableCriteriaHelper.SetProjection(products, criteria, "Product");
        LocalizableCriteriaHelper.SetResultTransformer(products, criteria);

        criteria.Add(Property.ForName("CategoryId").Eq(categoryId));

        return criteria.List().Cast<IProduct>();
      }
    }
  }
}
